package com.sh.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//@Service
public class UdpReceiverService {

    private final DatagramSocket socket;
    private volatile String latestData = "";
    private volatile boolean running = true;

    public UdpReceiverService(DatagramSocket socket) {
        this.socket = socket;
        // 构造函数中不再直接启动监听
    }

    @PostConstruct // 在Bean初始化完成后启动监听
    public void init() {
        startListeningAsync();
    }

    @Async
    public void startListeningAsync() {
        byte[] buffer = new byte[1024];
        while (running) {
            try {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet); // 阻塞操作，但运行在异步线程
                latestData = new String(packet.getData(), 0, packet.getLength());
            } catch (SocketException e) {
                if (!running) break; // 预期中的关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        running = false;
        socket.close(); // 关闭Socket释放资源
    }

    public String getLatestData() {
        return latestData;
    }
}